package com.sh.cloudrender.application.web.controller;


import com.sh.cloudrender.application.dto.engine.EngineDTO;
import com.sh.cloudrender.application.service.EngineService;
import com.sh.cloudrender.application.web.params.ApplyEngineParam;
import com.sh.cloudrender.application.web.params.QueryEngineParam;
import com.sh.cloudrender.application.web.params.ReleaseEngineParam;
import com.sh.cloudrender.common.dto.ShXResponse;
import com.sh.cloudrender.common.utils.ShXResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Validated
@RestController
@RequestMapping("/api/v1/engine")
public class EngineController {

    @Value("${engine.namespace}")
    private String namespace;

    @Autowired
    private EngineService engineService;


    @ResponseBody
    @PostMapping("/apply")
    public ShXResponse<EngineDTO> apply(@Valid @RequestBody ApplyEngineParam param) {
        EngineDTO dto = engineService.apply(param.getUserId(), param.getEngineName(), param.getSpec(), param.getEngineImage());
        return ShXResponseUtil.build(200, "apply engine success", dto);
    }

    @ResponseBody
    @PostMapping("/release")
    public ShXResponse<Void> release(@Valid @RequestBody ReleaseEngineParam param) {
        if (!engineService.release(param.getUserId(), param.getEngineId())) {
            return ShXResponseUtil.build(500, "release engine failed!", null);
        }

        return ShXResponseUtil.build(200, "release engine success", null);
    }


    @ResponseBody
    @PostMapping("/list")
    public ShXResponse<List<EngineDTO>> list(@Valid @RequestBody QueryEngineParam queryEngineParam) {
        List<EngineDTO> list = engineService.listBy(queryEngineParam.getUserId());
        return ShXResponseUtil.build(200, "list engine success", list);
    }
}
